package cn.cqzaier.pub.api.plugin.base.reqeust.cutecat;

import cn.cqzaier.pub.api.RequestApiUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.function.Function;

@Slf4j
public class CuteCatRequestUtil<T extends CuteCatRebootRequest, R> extends RequestApiUtil {
    private  String requstUrl;

    private boolean health;

    public CuteCatRequestUtil(String requstUrl) {
        this.requstUrl = requstUrl;
    }

    public String getRequstUrl() {
        return requstUrl;
    }

    public boolean isHealth() {
        return health;
    }

    public R doReq(T t, Function<String,R> function){
//        log.info("threadId-{} requestPost-url:{}",getThreadId(), requstUrl);
        log.info("threadId-{} requestPost-param:{}",getThreadId(), JSON.toJSONString(t));
        String s = HttpUtil.post(requstUrl,  JSON.toJSONString(t),3000);
        if (StringUtils.isBlank(s)){
            this.health = false;
            return null;
        }
        if (JSONUtil.toBean(s,Map.class).get("code").toString().equals("0")){
            this.health = true;
        }
        log.info("threadId-{} requestPost-result:{}",getThreadId(), s);
        return function.apply(s);
    }

    public long getThreadId(){
        return Thread.currentThread().getId();
    }

}
